package com.treasure.mall.zbqmallapi.controller.marketing;

import com.treasure.mall.biz.bo.config.SignConfig;
import com.treasure.mall.biz.entity.marketing.UserSignInPO;
import com.treasure.mall.biz.entity.user.UserPO;
import com.treasure.mall.biz.service.core.BaseConfigService;
import com.treasure.mall.biz.service.core.marketing.UserSignInService;
import com.treasure.mall.zbq.common.annotation.CurrentUser;
import com.treasure.mall.zbq.common.base.ApiResult;
import com.treasure.mall.zbqmallapi.annotation.AccessControl;
import com.treasure.mall.zbqmallapi.vo.integral.UserSignInLogVO;
import com.treasure.mall.zbqmallapi.vo.integral.UserSignInVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author allan
 * @version 1.0.0
 * @date 2020/8/25
 */
@RestController
@RequestMapping("/user/signIn")
@AccessControl(needLogin = true)
public class UserSignInController {
    @Resource
    private UserSignInService userSignInService;
    @Autowired
    private BaseConfigService baseConfigService;

    @PostMapping("/sign")
    public ApiResult sign(@CurrentUser UserPO userPO) {
        userSignInService.signIn(userPO.getUserId());

        return ApiResult.ok();
    }

    /**
     * 签到记录
     *
     * @param userPO
     * @return
     */
    @GetMapping("/logs")
    public ApiResult logs(@CurrentUser UserPO userPO) {
        List<UserSignInPO> pos = userSignInService.logs(userPO.getUserId());
        List<UserSignInLogVO> vos = pos.stream().map(UserSignInLogVO::new).collect(Collectors.toList());

        return ApiResult.ok(vos);
    }

    /**
     * 今日是否签到
     *
     * @param userPO
     * @return
     */
    @GetMapping("/isSigned")
    public ApiResult signed(@CurrentUser UserPO userPO) {
        UserSignInVO vo = new UserSignInVO();
        LocalDate now = LocalDate.now();
        //今天的
        UserSignInPO today = userSignInService.findByDate(userPO.getUserId(), now);
        if (today == null) {
            //上一次的
            UserSignInPO yesterday = userSignInService.findByDate(userPO.getUserId(), now.minusDays(1));
            if (yesterday == null) {
                vo.setContinueCount(0);
            } else {
                vo.setContinueCount(yesterday.getContinueNum());
            }
        } else {
            vo.setContinueCount(today.getContinueNum());
            vo.setSigned(true);
        }

        SignConfig signConfig = baseConfigService.getSignConfig();
        vo.setConfigList(signConfig.getRewardConfig());
        vo.setSubscribeRewardIntegral(signConfig.getSubscribeRewardIntegral());
        return ApiResult.ok(vo);
    }
}
